package cn.kgc.controller;

import cn.kgc.entity.Emp;
import cn.kgc.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
public class EmpController {
    @Autowired
    private EmpService empService;

    @GetMapping({"/emp/{pageNo}/{pageSize}","/emp"})
    public String getAllMap(@PathVariable(required = false,value = "pageNo") Integer pageNo,
                            @PathVariable(required = false,value = "pageSize") Integer pageSize,
                            Model model){
        if (pageNo == null){
            pageNo = 1;
        }
        if (pageSize == null){
            pageSize = 5;
        }
        List<Emp> empList = empService.getAllEmp(pageNo,pageSize);
        model.addAttribute("empList", empList);
        model.addAttribute("pageNo", pageNo);
        model.addAttribute("pageSize", pageSize);

        Integer count = empService.countEmp();
        Integer pageCount = count%pageSize== 0 ? count/pageSize : count/pageSize+1;
        model.addAttribute("pageCount", pageCount);
        return "empList";
    }

    @GetMapping("/emp/{id}")
    public String getEmpById(@PathVariable("id") Integer id, Model model){
        Emp emp = empService.getEmpById(id);
        model.addAttribute("emp", emp);
        return "emp";
    }

    @PostMapping("/emp")
    public String addEmp(Emp emp){
        empService.addEmp(emp);
        return "redirect:/emp";
    }

    @PutMapping("/emp")
    public String updateEmp(Emp emp){
        empService.updateEmp(emp);
        return "redirect:/emp";
    }

    @DeleteMapping("/emp/{id}")
    public String deleteEmp(@PathVariable("id") Integer id){
        empService.deleteEmpById(id);
        return "redirect:/emp";
    }

    @GetMapping("/emp/ui")
    public String toEmpUi(Model model){
        model.addAttribute("emp",new Emp());
        return "emp";
    }

    @GetMapping("/emp/name/{name}")
    @ResponseBody
    public Map<String,Object> countEmpByName(@PathVariable("name") String name){
        Integer count = empService.countEmpByName(name);
        Map<String,Object> data =new HashMap<>();
        data.put("count",count);
        return data;
    }

    @GetMapping("/emp/json/{id}")
    @ResponseBody
    public Emp getEmpById2(@PathVariable("id") Integer id){
        Emp emp = empService.getEmpById(id);
        return emp;
    }

    @PostMapping("/emp/json")
    @ResponseBody
    public String addEmp2(@RequestBody Emp emp){
        empService.addEmp(emp);
        return "ok";
    }
}
